/* 封装ajax函数
 * @param {string}option.method http连接的方式，包括POST和GET两种方式，默认使用GET
 * @param {string}option.url 发送请求的url
 * @param {boolean}option.async 是否为异步请求，true为异步的，false为同步的
 * @param {object}option.data 发送的参数，格式为对象类型
 * @param {function}option.success ajax发送并接收成功调用的回调函数
 */
function ajax(option) {
    option = option || {};

    var method = option.method || 'GET';
    method = method.toUpperCase() || 'GET';
    var url = option.url || '';
    var async = option.async || true;
    var data = option.data || null;
    var success = option.success || function () {
    };
    var xmlHttp = null;
    if (XMLHttpRequest) {
        xmlHttp = new XMLHttpRequest();
    }
    else {
        xmlHttp = new ActiveXObject('Microsoft.XMLHTTP');
    }
    var params = [];
    for (var key in data) {
        params.push(key + '=' + data[key]);
    }
    var dataStr = params.join('&');
    if (method === 'POST') {
        xmlHttp.open(method, url, async);
        xmlHttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded;charset=utf-8');
        xmlHttp.send(dataStr);
    }
    else {
        xmlHttp.open(method, url + '?' + dataStr, async);
        xmlHttp.send(null);
    }
    xmlHttp.onreadystatechange = function () {
        if (xmlHttp.readyState == 4 && xmlHttp.status == 200) {
            success(xmlHttp.responseText);
        }
    };
}

/* 表单验证 + ajax处理函数
 * @param selector : 通过ID或者class选择器获取的form表单对象，例如$('#myForm')
 * @param ajaxOption: 异步交互的设置项对象，包含method，url，data，success，error，async，所有设置项均有默认操作
 * @param msgCallback: 验证消息提示回调，默认调用light7的toast弹窗
 */
var checkform = function (selector, ajaxOption, confirmCallback, msgCallback) {
    var options = {
        success: function (result) {
            //检验重复提交
            if ($("button[type='submit']").hasClass('mui-disabled') || $("input[type='submit']").hasClass('mui-disabled')) {
                $('.cxvalidation_tip').html('请勿重复提交').addClass('show');
                return;
            }
            //验证成功禁用提交
            $("button[type='submit']").addClass('mui-disabled').attr('disabled', true);
            $("input[type='submit']").addClass('mui-disabled').attr('disabled', true);
            var method = ajaxOption.method || 'GET';
            method = method.toUpperCase() || 'GET';
            var url = ajaxOption.url || '';
            var async = ajaxOption.async || true;
            var data = ajaxOption.data || null;
            var dataType = ajaxOption.dataType || 'json';
            var confirm = ajaxOption.confirm || false;
            var alert_type = ajaxOption.alert_type || 0;
            var confirm_title = ajaxOption.confirm_title || '';
            var confirm_content = ajaxOption.confirm_content || '是否提交当前表单 ？';
            var alert = ajaxOption.alert || false;
            var dataStr = '';
            if (data) {
                var params = [];
                for (var key in data) {
                    params.push(key + '=' + data[key]);
                }
                dataStr = params.join('&');
            }
            var paramData = selector.serialize();
            if (dataStr != '' && dataStr != undefined) {
                paramData += '&' + dataStr;
            }
            var dealAjax = function (status) {
                if (status) {
                    $.ajax({
                        type: method,
                        url: url,
                        data: paramData,
                        dataType: dataType,
                        async: async,
                        success: function (res) {
                            console.log(res)
                            var ajaxres = res;
                            if (typeof(res) != 'object') {
                                ajaxres = JSON.parse(res);
                            }
                            if (ajaxres.status == 1) {
                                if (ajaxres.msg != '' && ajaxres.msg != undefined) {
                                    $('.cxvalidation_tip').css('background-color', 'rgb(64,196,2)');
                                    $('.cxvalidation_tip').html(ajaxres.msg).addClass('show');
                                }
                                if (ajaxOption.success && typeof(ajaxOption.success) == 'function') {
                                    if (ajaxres.msg != '' && ajaxres.msg != undefined) {
                                        setTimeout(function () {
                                            ajaxOption.success(ajaxres);
                                        }, 2000);
                                    } else {
                                        ajaxOption.success(ajaxres);
                                    }
                                }
                            } else {
                                var msg = '';
                                if (ajaxres.msg != '' && ajaxres.msg != undefined) {
                                    msg = ajaxres.msg;
                                } else {
                                    msg = '未知错误';
                                }
                                $('.cxvalidation_tip').html(msg).addClass('show');
                                if (ajaxOption.error && typeof(ajaxOption.error) == 'function') {
                                    if (ajaxres.msg != '' && ajaxres.msg != undefined) {
                                        setTimeout(function () {
                                            ajaxOption.error(ajaxres);
                                        }, 3000);
                                    } else {
                                        ajaxOption.error(ajaxres);
                                    }
                                }
                            }
                            var closeTipWait = setTimeout(function () {
                                $('.cxvalidation_tip').removeClass('show');
                                $('.cxvalidation_tip').css('background-color', 'orangered');
                                //请求成功开启提交
                                $("button[type='submit']").removeClass('mui-disabled').removeAttr('disabled');
                                $("input[type='submit']").removeClass('mui-disabled').removeAttr('disabled');
                            }, 3000);
                        },
                        error: function () {
                            $('.cxvalidation_tip').html('请求失败').addClass('show');
                            var closeTipWait = setTimeout(function () {
                                $('.cxvalidation_tip').removeClass('show');
                                //请求成功开启提交
                                $("button[type='submit']").removeClass('mui-disabled').removeAttr('disabled');
                                $("input[type='submit']").removeClass('mui-disabled').removeAttr('disabled');
                            }, 3000);
                        }
                    });
                }
            }
            if (confirm) {
                var confirmFlag = true;
                var new_confirm_content = confirm_content;
                if (confirm_content instanceof Array) {
                    new_confirm_content = eval(confirm_content[0])();
                }
                mui.confirm(new_confirm_content, confirm_title, ['确定', '取消'], function (e) {
                    if (e.index == 0) {
                        if (confirmFlag) {
                            dealAjax(true);
                        }
                        confirmFlag = false;
                    } else {
                        $('.cxvalidation_tip').removeClass('show');
                        //开启提交
                        $("button[type='submit']").removeClass('mui-disabled').removeAttr('disabled');
                        $("input[type='submit']").removeClass('mui-disabled').removeAttr('disabled');
                    }
                });
            } else if (alert) {
                var new_confirm_content = confirm_content;
                if (confirm_content instanceof Array) {
                    new_confirm_content = eval(confirm_content[0])();
                }
                mui.alert(new_confirm_content, confirm_title, '确定', function (e) {
                    $('.cxvalidation_tip').removeClass('show');
                    //开启提交
                    $("button[type='submit']").removeClass('mui-disabled').removeAttr('disabled');
                    $("input[type='submit']").removeClass('mui-disabled').removeAttr('disabled');
                    if (alert_type == 1) {
                        redirect('cart.html');
                    }
                });
            } else {
                dealAjax(true);
            }

        },


    };
    if (msgCallback != '' && msgCallback != undefined && typeof(msgCallback) == 'function') {
        options['error'] = msgCallback;
    }
    $.cxValidation.attach(selector, options);
}

//get方法
function getData(url, data, success, error) {
    if (url == '' || url == undefined) {
        return;
    }
    var paramData = '';
    if (data) {
        var params = [];
        for (var key in data) {
            params.push(key + '=' + data[key]);
        }
        paramData = params.join('&');
    }
    $.ajax({
        type: 'GET',
        url: url,
        data: paramData,
        success: function (res) {
            var ajaxres = res;
            if (typeof(res) != 'object') {
                ajaxres = JSON.parse(res);
            }
            if (ajaxres.msg != '' && ajaxres.msg != undefined) {
                malert(ajaxres.msg, function () {
                    if (ajaxres.msg == '未授权访问') {
                        logout();
                        return;
                    }
                });
            }
            if (ajaxres.status == 1) {
                if (success && typeof(success) == 'function') {
                    success(ajaxres);
                }
            } else {
                if (error && typeof(error) == 'function') {
                    error(ajaxres);
                }
            }
        },
        error: function () {
            mui.toast('请求失败');
        }
    });
}

//post方法
function postData(url, data, success, error) {
    if (url == '' || url == undefined) {
        return;
    }
    $.ajax({
        type: 'POST',
        url: url,
        data: data,
        success: function (res) {
            var ajaxres = res;
            if (typeof(res) != 'object') {
                ajaxres = JSON.parse(res);
            }
            if (ajaxres.msg != '' && ajaxres.msg != undefined) {
                malert(ajaxres.msg, function () {
                    if (ajaxres.msg == '未授权访问') {
                        logout();
                        return;
                    }
                });
            }
            if (ajaxres.status == 1) {
                if (success && typeof(success) == 'function') {
                    success(ajaxres);
                }
            } else {
                if (error && typeof(error) == 'function') {
                    error(ajaxres);
                }
            }
        },
        error: function () {
            malert('请求失败');
        }
    });
}

//页面跳转
function redirect(url) {
    var flag = url.indexOf('?');
    if (flag > 0) {
        window.location.href = url + '&_=' + timestamp;
        return;
    }
    window.location.href = url + '?_=' + timestamp;
    return;
}

function locationReplace(url) {
    var flag = url.indexOf('?');
    if (flag > 0) {
        url += '&_=' + timestamp;
    } else {
        url += '?_=' + timestamp;
    }
    location.replace(url);
}

//设置缓存
var loca_data = {
    xcx_openid: 'ocu9M5UUeFIb5mp-NofxMGpg6VXc',
    sid: 1,
    mid: 10021,
    nickname: '白茶清欢无别事',
    aid: 1,
    shop_name: '智宸水店'
}

function setCache(key, loca_data) {
    if (!window.localStorage) {
        $.alert('浏览器不支持localstorage');
    } else {
        var storage = window.localStorage;
        storage.setItem(key, JSON.stringify(loca_data));
    }
}

//获取缓存
function getCache(key) {
    if (!window.localStorage) {
        $.alert('浏览器不支持localstorage');
    } else {
        var storage = window.localStorage;
        return JSON.parse(storage.getItem(key));
    }
}

//删除缓存
function deleteCache(key) {
    if (!window.localStorage) {
        $.alert('浏览器不支持localstorage');
    } else {
        var storage = window.localStorage;
        storage.removeItem(key);
    }
}

//封装过期控制代码
function setCache_outTime(key, value) {
    if (!window.localStorage) {
        $.alert('浏览器不支持localstorage');
    } else {
        var curTime = new Date().getTime();
        localStorage.setItem(key, JSON.stringify({data: value, time: curTime}));
    }

}

function getCache_outTime(key, exp) {
    var data = localStorage.getItem(key);
    var dataObj = JSON.parse(data);
    var now_time = new Date().getTime();
    if (now_time / 1000 - dataObj.time / 1000 > exp) {
        console.log('信息已过期');
        return false;
    } else {
        var dataObjDatatoJson = dataObj.data;
        return dataObjDatatoJson;
    }
}

//检查登录状态，未登录跳转到登录页
function checkLogin() {
    var member_info = getCache(login_key)
    if (member_info == '' || member_info == undefined) {
        if (window.__wxjs_environment === 'miniprogram') {
            wx.miniProgram.redirectTo({url: '/pages/index/index?type=clear'});
        } else {
            if (is_local) {
                locationReplace('index.html');
            } else {
                window.opener = null;
                window.open('', '_self');
                window.close();
                return;
            }
        }
    }
}

function logout(type) {
    var newtype = type || 0;
    var member_info = getCache(login_key);
    var aid = 0;
    if (member_info) {
        aid = member_info.aid;
    }
    clearCart();
    clearMember();
    var weixin = is_weixn();
    if (window.__wxjs_environment === 'miniprogram') {
        wx.miniProgram.redirectTo({url: '/pages/index/index?type=clear'});
    } else {
        if (is_local) {
            locationReplace('index.html');
        } else if (weixin) {
            if (newtype > 0 || !aid) {
                window.opener = null;
                window.open('', '_self');
                window.close();
                return;
            } else {
                locationReplace(entrance + '/' + aid);
            }
        }
    }
}


//从地址里面拿参数
function GetQueryString(name) {
    var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
    var r = window.location.search.substr(1).match(reg);
    if (r != null) return unescape(r[2]);
    return null;
}

//获取地址栏参数//可以是中文参数
function getUrlParam(key) {
    // 获取参数
    var url = window.location.search;
    // 正则筛选地址栏
    var reg = new RegExp("(^|&)" + key + "=([^&]*)(&|$)");
    // 匹配目标参数
    var result = url.substr(1).match(reg);
    //返回参数值
    return result ? decodeURIComponent(result[2]) : null;
}

function GetUrlString(url, name) {
    console.log(url)
    if (url.indexOf('?') != -1) {
        url = url.split('?')[1];
        console.log(url)
    }
    var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
    var r = url.match(reg);
    if (r != null) return unescape(r[2]);
    return null;
}

//添加时间戳
var timestamp = new Date().getTime();

//通用请求参数 用法 getData('http://wwww.xxx.com',comParams(),success);
var comParams = function () {
    var member_info = getCache(login_key)
    if (member_info != '' && member_info != undefined) {
        var wx_openid = member_info.wx_openid || '';
        var xcx_openid = member_info.xcx_openid || '';
        if (window.__wxjs_environment == 'miniprogram') {
            wx_openid = '';
        }
        var sid = member_info.sid || '';
        return {xcx_openid: xcx_openid, wx_openid: wx_openid, sid: sid}
    }
    return {};
}

//联合请求参数 ，在通用参数基础上整合新的参数，用法 getData('http://wwww.xxx.com',combineParams({param:value}),success);
function combineParams(params) {
    var newParams = comParams();
    for (var n in params) {
        // eval('newParams.' + n + '=' + params[n]);
        newParams[n] = params[n];
    }
    return newParams;
}

function getScreen(maxW, maxH) {
    var arr = [
        document.documentElement.clientWidth || document.body.clientWidth,
        document.documentElement.clientHeight || document.body.clientHeigth
    ];
    maxW && (function () {
        if (arr[0] > maxW) {
            arr[0] = maxW;
        }
    }());
    maxH && (function () {
        if (arr[1] > maxH) {
            arr[1] = maxH;
        }
    }());
    return arr;
}

//给页面底部导航标签绑定点击事件，进行跳转
mui('.mui-bar-tab').on('tap', 'a', function () {
    window.top.location.href = this.href;
});

mui('.mui-bar').on('tap', '.mui-action-back', function () {
    if (history.length > 1) {
        history.go(-1);
        return false;
    }
    locationReplace('index.html');
});

//---------------------------------------------------分页 start------------------------------------------------------
/*
 * 具体使用方法：
 *   在需要使用分页功能页面配置主要业务参数即可，例如：
 *   fenye_options.url = 'http://www.xxxx.com/xxx';
 *   fenye_options.scrollHeight = '500px';
 *   fenye_options.dataName = 'goods_list';
 *   fenye_options.params = {category_id:1};
 *   fenye_options.callback = test;
 */

//分页功能辅助参数
var page = 1;           //页码
var is_more = true;     //是否有下一页
var minNum = 4;         //最小数据长度
var dataNum = 0;        //当前数据长度
//分页功能主要业务参数
var fenye_options = {
    url: '',                   //ajax请求接口
    originalData: '',          //原始数据，如果有原始数据则不调用url接口
    domNode: '#fenye_list',    //数据渲染节点
    scrollNode: '#scroll',     //分页列表滚动容器节点
    scrollHeight: '350px',     //滚动容器高度
    tmpId: 'fenye_list_data',  //模板ID
    tmpImports: {},            //模板助手，渲染页面时引入额外变量或函数,对象的形式：{name:value}
    dataName: '',              //需要渲染的响应数据名称
    params: {},                //ajax请求额外参数
    callback: ''               //设置分页内部执行的回调函数
};
//初始化分页功能
mui.init({
    pullRefresh: {
        container: fenye_options.scrollNode,//待刷新区域标识，querySelector能定位的css选择器均可，比如：id、.class等
        up: {
            height: 50,//可选.默认50.触发上拉加载拖动距离
            auto: true,//可选,默认false.自动上拉加载一次
            contentrefresh: "正在加载...",//可选，正在加载状态时，上拉加载控件上显示的标题内容
            contentnomore: '没有更多数据了',//可选，请求完毕若没有更多数据时显示的提醒内容；
            callback: fenye //必选，刷新函数，根据具体业务来编写，比如通过ajax从服务器获取新数据；
        }
    }
});

//主要分页功能函数
function fenye() {
    var success = function (res) {
        var data_list = res.data[fenye_options.dataName];
        if (data_list.next_page_url) {
            page += 1;
            mui(fenye_options.scrollNode).pullRefresh().endPullupToRefresh(false);
        } else {
            is_more = false;
            mui(fenye_options.scrollNode).pullRefresh().endPullupToRefresh(true);
        }
        dataNum = data_list.data.length;
        if (typeof(fenye_options.tmpImports) == 'object') {
            for (var i in fenye_options.tmpImports) {
                if (fenye_options.tmpImports[i] && typeof(fenye_options.tmpImports[i]) == 'function') {
                    template.defaults.imports[i] = fenye_options.tmpImports.value(res);
                } else {
                    template.defaults.imports[i] = fenye_options.tmpImports[i];
                }
            }
        }
        var html = template(fenye_options.tmpId, data_list);
        var str = html.replace(/[\r\n]/g, "").replace(/\ +/g, "").trim();
        if (page == 1 && str == '') {
            html = '<div class="no_data" style="align-content: center;height: ' + fenye_options.scrollHeight + ';padding-top: 50%;text-align: center;font-size: 20px;color: lightgray;">空空如也</div>';
        }
        $(fenye_options.domNode).append(html);
        //如果当前页是第一页且数据量不够滚动加载页面高度则结束上拉加载
        if (page == 1 && minNum > dataNum) {
            mui(fenye_options.scrollNode).pullRefresh().endPullupToRefresh(true);
            mui(fenye_options.scrollNode).pullRefresh().disablePullupToRefresh();
        } else if (!is_more) {
            //2s后提示性文字消失
            setTimeout(function () {
                mui(fenye_options.scrollNode).pullRefresh().disablePullupToRefresh();
            }, 2000);
        }
        if (fenye_options.callback && typeof(fenye_options.callback) == 'function') {
            fenye_options.callback(res);
        }
    };
    if (fenye_options.originalData != '') {
        success(fenye_options.originalData);
    } else {
        var newParams = {page: page};
        for (var n in fenye_options.params) {
            newParams[n] = fenye_options.params[n];
        }
        if (is_more && fenye_options.url) {
            getData(fenye_options.url, combineParams(newParams), success);
        }
    }
}

//---------------------------------------------------分页 end------------------------------------------------------

function getCartKey() {
    var memberInfo = getCache(login_key);
    if (memberInfo) {
        var xcx_openid = memberInfo.xcx_openid || '1';
        var wx_openid = memberInfo.wx_openid || '1';
        return 'cart_' + xcx_openid + '_' + wx_openid + '_' + memberInfo.sid;
    }
}


function addCart(goodsData, type) {
    var cartData = getCache(getCartKey()) || {};
    var num = Object.keys(cartData).length;
    if (num >= 10) {
        malert('购物车最多添加10件商品');
        return;
    }
    cartData[goodsData.id] = goodsData;
    setCache(getCartKey(), cartData);
    if (type == undefined) {
        mui.toast('添加购物车成功');
    }
    $("#gds_num").text(Object.keys(getCache(getCartKey())).length);
}

function getCartList() {
    return getCache(getCartKey()) || {};
}

function delCart(goods_id) {
    var cartData = getCartList() || {};
    var num = Object.keys(cartData).length;
    if (num <= 0) {
        return;
    }
    delete cartData[goods_id];
    setCache(getCartKey(), cartData);
    $("#gds_num").text(num - 1);
}

function clearCart() {
    if (!window.localStorage) {
        $.alert('浏览器不支持localstorage');
    } else {
        var storage = window.localStorage;
        storage.removeItem(getCartKey());
    }
}

function clearMember() {
    if (!window.localStorage) {
        $.alert('浏览器不支持localstorage');
    } else {
        var storage = window.localStorage;
        storage.removeItem(login_key);
    }
}

function showGdsNum() {
    var cartData = getCache(getCartKey()) || {};
    var num = Object.keys(cartData).length;
    $("#gds_num").text(num);
}


if (is_local) { /* ocu9M5UAUDeJkNAapQHWWw5u1zPg*/
    /*ocu9M5XnRWEz9AU0WG2G4wddvmZk*/
    setCache(login_key, {
        xcx_openid: 'ocu9M5UAUDeJkNAapQHWWw5u1zPg', /* ocu9M5UAUDeJkNAapQHWWw5u1zPg*/
        wx_openid:'', /*otGWCxKskngtEgE81vHrJtZOmhsk*/
        sid: 1,
        aid: 1,  //1
        mid:100000,
        shop_name: '智宸水店',
        mobile: '1302587856',
        buy_min: 2,
        buy_max: 12,
        withdraw_min:20
       /* mid:19*/
    });
} else {
    login();
}

var h = document.getElementsByTagName('header');
remove(h);

if (window.__wxjs_environment !== 'miniprogram') {
    recover(h);
}

if (is_local) {
    recover(h);
}

function remove(selectors) {
    selectors.removeNode = [];
    if (selectors.length != undefined) {
        var len = selectors.length;
        for (var i = 0; i < len; i++) {
            selectors.removeNode.push({
                parent: selectors[i].parentNode,
                inner: selectors[i].outerHTML,
                next: selectors[i].nextSibling
            });
        }
        for (var i = 0; i < len; i++)
            selectors[0].parentNode.removeChild(selectors[0]);
    }
    else {
        selectors.removeNode.push({
            parent: selectors.parentNode,
            inner: selectors.outerHTML,
            next: selectors.nextSibling
        });
        selectors.parentNode.removeChild(selectors);
    }
}

function recover(selectors) {
    var len = selectors.removeNode.length;
    for (var i = 0; i < len; i++) {
        var node = selectors.removeNode[i];
        if (node.next == null)
            node.parent.innerHTML += node.inner;
        else {
            var div = document.createElement("div");
            div.innerHTML = node.inner;
            node.parent.insertBefore(div.childNodes[0], node.next);
        }
    }
}


function tolog(data) {
    getData(siteUrl + 'server/tolog', {data: data});
}

//获取用户登录信息
function login() {
    var params = GetQueryString('params');
    if (params) {
        var member_info = JSON.parse(unescape(params));
        setCache(login_key, member_info);
    }
}

function is_weixn() {
    var ua = navigator.userAgent.toLowerCase();
    if (ua.match(/MicroMessenger/i) == "micromessenger") {
        return true;
    } else {
        return false;
    }
}

function checkBack() {
    if (window.history && window.history.pushState) {
        $(window).on('popstate', function () {
            window.history.pushState('forward', null, '#');
            window.history.forward(1);
            // mui.alert("不可回退");
        });
    }
}

//非空判断
function isEmpty(data) {
    if (data == undefined || data == null || data == '') {
        return true;
    } else {
        return false;
    }
}

function checkShopStatus() {
    var success = function (res) {
        var status = parseInt(res.data.shop_status);
        if (status < 0) {
            checkBack();
            redirect('call_person.html');
        }
    }
    getData(check_shop_status, comParams(), success);
}


//获取当前时间
function getNowFormatDate() {
    var date = new Date();
    var seperator1 = "-";
    var seperator2 = ":";
    var month = date.getMonth() + 1;
    var strDate = date.getDate();
    if (month >= 1 && month <= 9) {
        month = "0" + month;
    }
    if (strDate >= 0 && strDate <= 9) {
        strDate = "0" + strDate;
    }
    var currentdate = date.getFullYear() + seperator1 + month + seperator1 + strDate
        + " " + date.getHours() + seperator2 + date.getMinutes()
        + seperator2 + date.getSeconds();
    return currentdate;
}

//微信支付
var wxPay = function (params, type) {
    function onBridgeReady() {
        if (typeof WeixinJSBridge === 'undefined') {
            malert('请在微信在打开页面！');
            return false;
        }
        WeixinJSBridge.invoke(
            'getBrandWCPayRequest', {
                "appId": params.appId,     //公众号名称，由商户传入
                "timeStamp": params.timeStamp,         //时间戳，自1970年以来的秒数
                "nonceStr": params.nonceStr, //随机串
                "package": params.package,
                "signType": params.signType,         //微信签名方式：
                "paySign": params.paySign //微信签名
            },
            function (res) {
                switch (res.err_msg) {
                    case 'get_brand_wcpay_request:cancel':
                        malert('', '用户取消支付！', function () {
                            if (parseInt(type) == 1) {
                                locationReplace('index.html');
                            } else {
                                locationReplace('water-ticket.html');
                            }
                        });
                        break;
                    case 'get_brand_wcpay_request:fail':
                        malert(res.err_desc, '支付失败', function () {
                            locationReplace('fail.html?type=1');
                        });
                        break;
                    case 'get_brand_wcpay_request:ok':
                        clearCart();
                        locationReplace('success.html?type=' + type);
                        break;
                    default:
                        alert(JSON.stringify(res));
                        break;
                }
            });
    }

    if (typeof WeixinJSBridge == "undefined") {
        if (document.addEventListener) {
            document.addEventListener('WeixinJSBridgeReady', onBridgeReady, false);
        } else if (document.attachEvent) {
            document.attachEvent('WeixinJSBridgeReady', onBridgeReady);
            document.attachEvent('onWeixinJSBridgeReady', onBridgeReady);
        }
    } else {
        onBridgeReady();
    }
}

function malert(msg, title, btnValue, callback) {
    mui.alert('<div style="word-break: break-all; word-wrap:break-word;">' + msg + '</div>', title, btnValue, callback);
}
